from flask_restful import Resource, Api
from flask import Blueprint, request, session
from model import db
from libs.response import generate_response
from model.models import User

userapi_bp = Blueprint("userapi", __name__)
api = Api(userapi_bp)


class UserApi(Resource):

    def get(self):
        account = session.get("account")
        user = User.query.filter(User.account == account).first()
        result = {"id": user.id,
                  "account": account,
                  "password": "****",
                  "username": user.username,
                  "gender": user.gender}

        return generate_response(data=result, message="get success")

    def put(self):
        account = session.get("account")
        user = User.query.filter(User.account == account).first()

        user_info = request.get_json()

        try:
            for k in user_info:
                if k == "username":
                    user.username = user_info.get(k)
                elif k == "password":
                    user.password = user_info.get(k)
                elif k == "gender":
                    user.gender = user_info.get(k)
            db.session.commit()
            return generate_response(message="put success", status_code=2000)
        except Exception:
            return generate_response(message="put unsuccessful", status_code=4000)


api.add_resource(UserApi, "/userapi")
# api.add_resource(UserApi, "/userapi/<id>", endpoint='userapiid')
